import { useAuth } from '@/stores/useAuth';

export async function fetchWithAuth(
  input: RequestInfo,
  init: RequestInit = {}
): Promise<Response> {
  const auth = useAuth();
  let accessToken = auth.accessToken.value;
  const refreshToken = auth.refreshToken.value;

  if (!accessToken) throw new Error('No access token available');

  const makeRequest = async () => {
    return fetch(input, {
      ...init,
      headers: {
        ...(init.headers || {}),
        Authorization: `Bearer ${accessToken}`,
      },
    });
  };

  let resp = await makeRequest();

  if (resp.status === 401 && refreshToken) {
    const body = new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token: refreshToken,
      client_id: import.meta.env.VITE_CLIENT_ID as string,
    });

    const tokenResp = await fetch(
      `${import.meta.env.VITE_AUTHORITY}/connect/token`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: body.toString(),
      }
    );

    const tokenData = await tokenResp.json();
    if (!tokenResp.ok) throw new Error('Refresh token failed');

    accessToken = tokenData.access_token;
    if (!accessToken) throw new Error('Missing accessToken');
    auth.setTokens(accessToken, tokenData.refresh_token);

    resp = await makeRequest();
  }

  return resp;
}
